package com.bw.module_motorcircle.test_recyclerview

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bw.lib_widget.test.MyView
import com.bw.module_motorcircle.R
import com.bw.module_motorcircle.databinding.ItemTestBinding
import kotlin.math.log

/**
 * @author ytx
 * @date 2025-09-24 13:48
 * @description
 */
class MyAdapter:RecyclerView.Adapter<MyAdapter.MyViewHolder>(){
    companion object{
        private const val TAG = "MyAdapter"
    }
    private val list = ArrayList<MyModel>()
    fun setData(mList: List<MyModel>){
        list.clear()
        list.addAll(mList)
        notifyDataSetChanged()
    }

    /**
     * 追加数据，范围刷新
     */
    fun addData(mList: List<MyModel>){
        val start = list.size
        list.addAll(mList)
        notifyItemRangeInserted(start,mList.size)
    }

    /**
     * 删除数据
     */
    fun removeData(position: Int){
        list.removeAt(position)
        notifyItemRemoved(position)
    }

    /**
     * 修改数据:刷新整个item条目
     */
    fun update(position: Int){
        list.get(position).like =  ! list.get(position).like
        notifyItemChanged(position)
    }
    /**
     * 修改数据:只刷新爱心：局部增量刷新
     */
    fun updateLike(position: Int){
        list.get(position).like =  ! list.get(position).like
        notifyItemChanged(position,"like")
    }
    override fun onCreateViewHolder(parent: ViewGroup, position: Int): MyViewHolder {
        Log.d(TAG, "onCreateViewHolder: "+position)
        val binding = DataBindingUtil.inflate<ItemTestBinding>(LayoutInflater.from(parent.context), R.layout.item_test,parent,false)
        return MyViewHolder(binding)
    }

    override fun getItemCount(): Int {
       return list.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()){
            onBindViewHolder(holder,position) //刷新整个item条目
        }else{
            if (payloads.contains("like")){
                Log.d(TAG, "onBindViewHolder只刷新爱心: "+position)
                holder.binding.ivLike.isEnabled = list[position].like
            }
        }
    }

    override fun onBindViewHolder(viewHolder: MyViewHolder, position: Int) {
        Log.d(TAG, "onBindViewHolder: "+position)
        viewHolder.binding.myModel = list[position]
        viewHolder.binding.ivLike.isEnabled = list[position].like

    }

    class MyViewHolder(val binding:ItemTestBinding):RecyclerView.ViewHolder(binding.root)

}